//
//  WebViewController.swift
//  KFQ
//
//  Created by zhenyu on 12/14/16.
//  Copyright © 2016 qianshengqian. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON

class WebViewController: ViewController {
  
  weak var webView: EasyJSWebView!
  weak var backButton: UIButton!
  
  var urlString = ""
  
  let interface = MyJSData()
  var isHidden = false
  
  /// cos 上传图片路径
  var cosString = ""
  
  // 芝麻信用参数
  var zmAuthParams = [String: String]()
  
  // 上传图片回调JS参数
  var imageViewID = ""
  var callBackJSFunc = ""
  
  
  // MARK: - LifeCycle
  convenience init(url: String) {
    self.init()
    urlString = url
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    setViews()
    loadWebView(url: urlString)
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
  }
  
  
  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  
  // MARK: - SetViews
  func setViews() {
    webView = {
      let w = EasyJSWebView(frame: CGRect.zero)
      w.scrollView.bounces = false
      w.scrollView.showsVerticalScrollIndicator = false
      w.delegate = self
//      interface.delegate = self
//      w.addJavascriptInterfaces(interface, withName: "qsqapi")
      view.addSubview(w)
      w.snp.makeConstraints { (make) in
        make.top.left.bottom.right.equalTo(view)
      }
      return w
    }()
    
    let backImage = UIImageView(image: #imageLiteral(resourceName: "backImage"))
    let backView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 44))
    backView.addSubview(backImage)
    backImage.snp.makeConstraints { (make) in
      make.centerY.equalTo(backView)
      make.left.equalTo(backView)
    }
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(back))
    backView.addGestureRecognizer(tapGesture)
    let leftItem = UIBarButtonItem(customView: backView)
    navigationItem.leftBarButtonItem = leftItem
  }
  
  // MARK: - Action
  func loadWebView(url: String) {
    let url = URL(string: url)
    if let url = url {
      var req = URLRequest(url: url)
      req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
      req.setValue(User.token, forHTTPHeaderField: "X-User-Token")
      webView.loadRequest(req)
    }
  }
  
  func back() {
    if webView.canGoBack {
      webView.goBack()
    } else {
      _ = navigationController?.popViewController(animated: true)
    }
  }
  
  // MARK: - Method
  func reload() {
    webView.reload()
  }
}


// MARK: - UIWebViewDelegate
extension WebViewController: UIWebViewDelegate {
  func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    return true
  }
  
  func webViewDidFinishLoad(_ webView: UIWebView) {
    title = webView.stringByEvaluatingJavaScript(from: "document.title")
    debugPrint("url ======= \(webView.request?.url?.absoluteString)")

  }
  
  func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
  }
}


